#include "medicinesearchwidget.h"
#include "../../network/networkclient.h"
#include <QHeaderView>
#include <QMessageBox>
#include <QJsonArray>

MedicineSearchWidget::MedicineSearchWidget(QWidget *parent)
    : QWidget(parent)
{
    setupUI();
    
    // 连接网络消息
    connect(&NetworkClient::instance(), &NetworkClient::messageReceived,
            this, &MedicineSearchWidget::onMessageReceived);
    
    // 加载热门药物
    loadPopularMedicines();
}

MedicineSearchWidget::~MedicineSearchWidget() {
}

void MedicineSearchWidget::setupUI() {
    QVBoxLayout *mainLayout = new QVBoxLayout(this);
    mainLayout->setContentsMargins(20, 20, 20, 20);
    
    // 标题
    m_titleLabel = new QLabel("药物信息查询", this);
    m_titleLabel->setStyleSheet("font-size: 20px; font-weight: bold; color: #2c3e50;");
    m_titleLabel->setAlignment(Qt::AlignCenter);
    mainLayout->addWidget(m_titleLabel);
    
    // 搜索栏
    QHBoxLayout *searchLayout = new QHBoxLayout();
    QLabel *searchLabel = new QLabel("搜索药物:", this);
    searchLabel->setStyleSheet("font-size: 14px;");
    m_searchEdit = new QLineEdit(this);
    m_searchEdit->setPlaceholderText("输入药物名称或分类...");
    m_searchEdit->setStyleSheet("padding: 8px; font-size: 14px; border: 1px solid #ddd; border-radius: 4px;");
    m_searchButton = new QPushButton("搜索", this);
    m_searchButton->setStyleSheet(
        "QPushButton { padding: 8px 20px; font-size: 14px; background-color: #07C160; color: white; border: none; border-radius: 4px; }"
        "QPushButton:hover { background-color: #06AD56; }"
        "QPushButton:pressed { background-color: #059048; }");
    
    searchLayout->addWidget(searchLabel);
    searchLayout->addWidget(m_searchEdit, 1);
    searchLayout->addWidget(m_searchButton);
    mainLayout->addLayout(searchLayout);
    
    // 药物列表表格
    m_medicineTable = new QTableWidget(this);
    m_medicineTable->setColumnCount(5);
    m_medicineTable->setHorizontalHeaderLabels({"药物名称", "分类", "规格", "价格(元)", "厂家"});
    m_medicineTable->horizontalHeader()->setStretchLastSection(true);
    m_medicineTable->horizontalHeader()->setSectionResizeMode(0, QHeaderView::ResizeToContents);
    m_medicineTable->horizontalHeader()->setSectionResizeMode(1, QHeaderView::ResizeToContents);
    m_medicineTable->horizontalHeader()->setSectionResizeMode(2, QHeaderView::ResizeToContents);
    m_medicineTable->horizontalHeader()->setSectionResizeMode(3, QHeaderView::ResizeToContents);
    m_medicineTable->verticalHeader()->setVisible(false);  // 隐藏行号
    m_medicineTable->setSelectionBehavior(QAbstractItemView::SelectRows);
    m_medicineTable->setSelectionMode(QAbstractItemView::SingleSelection);
    m_medicineTable->setEditTriggers(QAbstractItemView::NoEditTriggers);
    m_medicineTable->setShowGrid(true);
    m_medicineTable->setGridStyle(Qt::SolidLine);
    m_medicineTable->setStyleSheet(
        "QTableWidget { "
        "   border: 1px solid #bdc3c7; "
        "   background-color: white; "
        "   gridline-color: #ecf0f1; "
        "}"
        "QHeaderView::section { "
        "   background-color: #2ecc71; "
        "   color: white; "
        "   padding: 10px; "
        "   border: none; "
        "   border-right: 1px solid #27ae60; "
        "   font-weight: bold; "
        "   font-size: 13px; "
        "}"
        "QTableWidget::item { "
        "   padding: 8px; "
        "   border-bottom: 1px solid #ecf0f1; "
        "}"
        "QTableWidget::item:selected { "
        "   background-color: #3498db; "
        "   color: white; "
        "}"
        "QTableWidget::item:hover { "
        "   background-color: #e8f5e9; "
        "}"
    );
    mainLayout->addWidget(m_medicineTable, 2);
    
    // 详细信息
    QLabel *detailLabel = new QLabel("详细信息 (点击表格行查看):", this);
    detailLabel->setStyleSheet("font-size: 14px; font-weight: bold; margin-top: 10px;");
    mainLayout->addWidget(detailLabel);
    
    m_detailText = new QTextEdit(this);
    m_detailText->setReadOnly(true);
    m_detailText->setStyleSheet("border: 1px solid #ddd; padding: 10px; background-color: #f8f9fa;");
    m_detailText->setPlaceholderText("选择药物后，此处将显示详细的使用说明和注意事项");
    mainLayout->addWidget(m_detailText, 1);
    
    // 连接信号
    connect(m_searchButton, &QPushButton::clicked, this, &MedicineSearchWidget::onSearchClicked);
    connect(m_searchEdit, &QLineEdit::returnPressed, this, &MedicineSearchWidget::onSearchClicked);
    connect(m_searchEdit, &QLineEdit::textChanged, this, &MedicineSearchWidget::onSearchTextChanged);
    connect(m_medicineTable, &QTableWidget::cellClicked, this, &MedicineSearchWidget::onMedicineSelected);
}

void MedicineSearchWidget::loadPopularMedicines() {
    QJsonObject request;
    NetworkClient::instance().sendRequest(MSG_GET_POPULAR_MEDICINES, request);
}

void MedicineSearchWidget::onSearchClicked() {
    QString keyword = m_searchEdit->text().trimmed();
    if (keyword.isEmpty()) {
        QMessageBox::warning(this, "提示", "请输入搜索关键词！");
        return;
    }
    
    QJsonObject request;
    request["keyword"] = keyword;
    NetworkClient::instance().sendRequest(MSG_SEARCH_MEDICINES, request);
}

void MedicineSearchWidget::onSearchTextChanged(const QString& text) {
    // 当搜索框清空时，恢复显示热门药物
    if (text.trimmed().isEmpty()) {
        loadPopularMedicines();
    }
}

void MedicineSearchWidget::onMedicineSelected(int row, int column) {
    Q_UNUSED(column);
    
    if (row < 0 || row >= m_medicineTable->rowCount()) {
        return;
    }
    
    // 从表格的userData中获取完整的药物信息
    QVariant userData = m_medicineTable->item(row, 0)->data(Qt::UserRole);
    if (!userData.isValid()) {
        return;
    }
    
    QJsonObject medicineData = userData.toJsonObject();
    Medicine medicine = Medicine::fromJson(medicineData);
    
    // 显示详细信息
    QString detail;
    detail += "<h3 style='color: #2c3e50;'>" + medicine.name + "</h3>";
    detail += "<p><b>分类：</b>" + medicine.category + "</p>";
    detail += "<p><b>生产厂家：</b>" + medicine.manufacturer + "</p>";
    detail += "<p><b>规格：</b>" + medicine.specification + "</p>";
    detail += "<p><b>参考价格：</b>¥" + QString::number(medicine.price, 'f', 2) + "</p>";
    detail += "<hr>";
    detail += "<h4 style='color: #27ae60;'>使用说明：</h4>";
    detail += "<p style='line-height: 1.6;'>" + medicine.usageInstruction + "</p>";
    detail += "<h4 style='color: #e74c3c;'>注意事项：</h4>";
    detail += "<p style='line-height: 1.6;'>" + medicine.precautions + "</p>";
    
    m_detailText->setHtml(detail);
}

void MedicineSearchWidget::displayMedicines(const QJsonArray& medicines) {
    m_medicineTable->setRowCount(0);
    
    for (int i = 0; i < medicines.size(); ++i) {
        QJsonObject medicineObj = medicines[i].toObject();
        Medicine medicine = Medicine::fromJson(medicineObj);
        
        int row = m_medicineTable->rowCount();
        m_medicineTable->insertRow(row);
        
        // 药物名称
        QTableWidgetItem *nameItem = new QTableWidgetItem(medicine.name);
        nameItem->setData(Qt::UserRole, medicineObj);  // 保存完整数据
        if (medicine.isPopular) {
            nameItem->setForeground(QBrush(QColor("#e74c3c")));
            nameItem->setFont(QFont("Arial", 10, QFont::Bold));
        }
        m_medicineTable->setItem(row, 0, nameItem);
        
        // 分类
        m_medicineTable->setItem(row, 1, new QTableWidgetItem(medicine.category));
        
        // 规格
        m_medicineTable->setItem(row, 2, new QTableWidgetItem(medicine.specification));
        
        // 价格
        m_medicineTable->setItem(row, 3, new QTableWidgetItem(QString::number(medicine.price, 'f', 2)));
        
        // 厂家
        m_medicineTable->setItem(row, 4, new QTableWidgetItem(medicine.manufacturer));
    }
    
    if (medicines.isEmpty()) {
        m_detailText->setPlainText("未找到相关药物");
    } else {
        m_detailText->setPlainText("请点击表格行查看药物详细信息");
    }
}

void MedicineSearchWidget::onMessageReceived(MessageType type, const QJsonObject& data) {
    if (type == MSG_GET_POPULAR_MEDICINES_RESPONSE) {
        if (data["success"].toBool()) {
            displayMedicines(data["medicines"].toArray());
        } else {
            QMessageBox::warning(this, "错误", "加载热门药物失败");
        }
    } else if (type == MSG_SEARCH_MEDICINES_RESPONSE) {
        if (data["success"].toBool()) {
            displayMedicines(data["medicines"].toArray());
            if (data["medicines"].toArray().isEmpty()) {
                QMessageBox::information(this, "提示", "未找到相关药物");
            }
        } else {
            QMessageBox::warning(this, "错误", "搜索失败");
        }
    }
}

